<!-- 设置公务号码所属分类 -->
<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    :body-style="{ height: '350px' }"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { moveToCategoryFormSchema } from './articles.data';
  import { moveArticlesToCategory } from '/@/api/cms/article';

  import { useMessage } from '/@/hooks/web/useMessage';

  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';

  import { queryListSimple } from '/@/api/cms/category'; // api
  import { CategoryQueryConditionDto } from '/@/api/cms/model/categoryModel';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetCategoryForPhones',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //接收父组件传递过来的数据对象
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      /**
       * 处理显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      //父组件传递过来的文章ID集合
      const dataIds = ref([]);

      const [registerForm, { resetFields, validate, updateSchema }] = useForm({
        labelWidth: 80,
        schemas: moveToCategoryFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log(data);
        //接收父组件传递的数据
        if (data != undefined && data != null) {
          qcUnifyProps.value = unref(data);
          console.log('接收的对象', data.dataId);
          dataIds.value = data.dataId;
        }

        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });

        getAllValidCategories();
      });

      /**
       * 获取所有有效的栏目集合，用于栏目下拉项回显
       */
      function getAllValidCategories() {
        //显示的栏目信息只包含有效状态，并且根据用户所在部门进行过滤
        let queryConditionDto: CategoryQueryConditionDto = {
          isall: false,
          isdept: true,
          isvisible: true,
        };
        queryListSimple(queryConditionDto)
          .then((res) => {
            console.log('getAllValidCategories res', res);
            let categoryOptions = [];
            res.forEach((category) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              let categoryId: number = category.id as number;
              //根据层级在栏目名称前添加空格，实测空格无效，显示时没有空格
              let prefixSpaces = '';
              for (let index = 1; index < category.level; index++) {
                prefixSpaces += '----';
              }
              categoryOptions.push({ value: categoryId, label: prefixSpaces + category.name });
            });

            updateSchema({
              field: 'cid',
              componentProps: {
                options: categoryOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，保存信息
       */
      async function onButtonOkClick() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          moveArticlesToCategory({ ids: dataIds.value, cid: values.cid })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('文章移动成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }

      return {
        displayModuleTitle,
        registerModal,
        registerForm,
        onButtonOkClick,
        opSuccess,
        getAllValidCategories,
      };
    },
  });
</script>
